<template>
	<view class="container">
		<view class="nav-bar">
			<text class="title">{{ paperTitle }}</text>
			<text class="current">{{ currentIndex + 1 }}/{{ questions.length }}</text>
		</view>
		<view class="question">
			<view class="question-title">
				<view v-html="currentQuestion.title" class="title"></view>
			</view>
			<scroll-view scroll-y="true" style="padding-bottom: 200rpx;">
				<view class="options-container">
					<view v-for="(option, idx) in currentQuestion.content_format" :key="idx" class="option-item" :class="{ selected: isOptionSelected(idx) }" @click="handleSelect(idx)">
						<view class="option-circle"></view>
						<!-- <view class="option-text">{{option}}</view> -->
						<view v-html="option" class="option-text"></view>
					</view>
					<textarea v-if="currentQuestion.type == 3" v-model="answer" @input="changeVal(currentQuestion)" class="answerarea" placeholder="请输入答题内容" />
				</view>
				<view class="analysis" v-if="analysisShow">
					<view class="tages" v-if="answerStatus">
						<image src="/static/dui.png"></image>
						<text>回答正确</text>
					</view>
					<view class="tages" v-if="!answerStatus">
						<image src="/static/cuowu.png"></image>
						<text>回答错误</text>
					</view>
					<view class="answers">
						<view class="tt"> 
							<text>答案</text>
							<view class="lines"> </view>
						</view>
						<view class="tta"> {{ currentQuestion.answer }} </view>
					</view>
					<view class="jiexi">
						<view class="tt"> 
							<text>解析</text>
							<view class="lines"> </view>
						</view>
						<view v-html="currentQuestion.analysis" class="tta" ref="analysis"  @tap="handleImageClick"></view>
					</view>
				</view>
			</scroll-view>
			<view class="bottom">
				<view class="icons" :disabled="currentIndex === 0" @click="prevQuestion">
					<image src="/static/prev.png" mode=""></image>
					<text>上一题</text>
				</view>
				<view class="icons" @click="shoucang" v-if="currentQuestion.is_collect == 0">
					<image src="/static/sc.png" mode=""></image>
					<text>收藏</text>
				</view>
				<view class="icons" @click="shoucang" v-if="currentQuestion.is_collect == 1">
					<image src="/static/yisc.png" mode=""></image>
					<text>已收藏</text>
				</view>
				<view class="icons" @click="datika">
					<image src="/static/dtk.png" mode=""></image>
					<text>答题卡</text>
				</view>
				<view class="icons" @click="nextQuestion">
					<image src="/static/next.png" mode=""></image>
					<text>{{ isLastQuestion ? '提交试卷' : '下一题' }}</text>
				</view>
			</view>
		</view>
	</view>
	<view class="loading" v-if="loading">
		<view class="load">
			<image src="/static/loading.png" mode=""></image>
		</view>
		<view class="modal"> </view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				questions: [], 
				currentIndex: 0,
				userAnswers: [],
				baseURL: getApp().globalData.baseUrl,
				appid: uni.getStorageSync('appid'),
				options: '',
				paperTitle: '',
				analysisShow: false,
				answerStatus: false,
				loading: false,
				record: [],
				tmp: [],
				answer: '',
				types: 2 //1 考试模式  2 练习模式
			};
		},
		computed: {
			currentQuestion() {
				return this.questions[this.currentIndex]?.questions || {};
			},
			// 解析后的选项
			parsedOptions() {
				const content = this.currentQuestion.content || '';
				console.log(this.currentQuestion.content_format)
				const optionRegex = /([A-D])：([^A-D]+)/g;
				const options = [];
				let match;
			  
				while ((match = optionRegex.exec(content)) !== null) {
					options.push({key: match[1],text: match[2].trim()});
				}
				return options;
			},
			// 是否是最后一题
			isLastQuestion() {
				return this.currentIndex === this.questions.length - 1;
			}
		},
		methods: {
			// 初始化数据
			initData(questions) {
				this.userAnswers = new Array(questions.length).fill(null).map(() => []);
				for( var i=0;i<questions.length;i++ ){
					questions[i].questions.is_collect = 0
					questions[i].questions.is_answer  = false
					if( this.record.length > 0 ){
						for( var j=0;j<this.record.length;j++ ){
							if( this.record[j].id == questions[i].id ){
								questions[i].questions.is_collect = this.record[j].is_collect
							}
						}
					}
					questions[i].questions.analysis  = this.processHtmlImages(questions[i].questions.analysis)
					const content = questions[i]?.questions.content_format;
					var arr = []
					if (content) {
						for( var j=0;j<content.length;j++ ){
							var tmp = content[j];
							tmp = tmp.replace(/src="/g, 'src="http://www.sdwxedu.com');
							if (questions[i]?.questions?.content_format) {
							    questions[i].questions.content_format[j] = tmp;
							}
						}
					}
				}
				this.questions = questions;
			},
			// 选项选择处理
			handleSelect(key) {
				if (this.currentQuestion.type === 1) {
					this.userAnswers[this.currentIndex] = [key];
				} else if(  this.currentQuestion.type === 2 ) {
					const index = this.userAnswers[this.currentIndex].indexOf(key);
					if (index > -1) {
						this.userAnswers[this.currentIndex].splice(index, 1);
					} else {
						this.userAnswers[this.currentIndex].push(key);
					}
				}
				this.matchAns()
			},
			// 判断选项是否选中
			isOptionSelected(key) {
				return this.userAnswers[this.currentIndex].includes(key);
			},
			// 上一题
			prevQuestion() {
				if (this.currentIndex > 0) {
					this.currentIndex--;
				}
				this.matchAns()
				this.answer = this.userAnswers[this.currentIndex]
			},
			// 下一题/提交
			nextQuestion() {
				var ans  = ''
				if( this.currentQuestion.type == 2 ){
					var options = this.currentQuestion.content_format
					var ans1 =  this.userAnswers[this.currentIndex]
					for(var j=0;j<ans1.length;j++){
						if( j == ans1.length - 1 ){
							ans += options[ans1[j]].split(':')[0]
						} else {
							ans += options[ans1[j]].split(':')[0] + ','
						}
					}
				} else if( this.currentQuestion.type == 3 ) {
					this.userAnswers[this.currentIndex]  = ans   =  this.answer
				} else {
					if(  this.currentQuestion.content_format[this.userAnswers[this.currentIndex]]  != undefined ){
						ans = this.currentQuestion.content_format[this.userAnswers[this.currentIndex]].split(':')[0]
					}
				}
				// if( ans ){
				// 	this.submitAnswers(ans);
				// }
				this.submitAnswers(ans);
				if (!this.isLastQuestion) {
					this.currentIndex++;
					if( this.currentQuestion.is_answer ){
						this.answer  =  this.userAnswers[this.currentIndex]
					} else {
						this.answer  =  ''
					}
				} else {
					var that  =  this
					uni.showToast({ title: '答题完成！' });
					setTimeout(function(){
						uni.navigateTo({
							url: '/pages/question/result?paper_id='+that.questions[0].paper_id
						})
					},500)
				}
				if( this.userAnswers[this.currentIndex].length == 0 ){
					this.analysisShow = false
					this.answerStatus = false
				}  else {
					this.matchAns()
				}
			},
			matchAns(){
				var ans  = ''
				if( this.currentQuestion.type == 2 ){
					var options = this.currentQuestion.content_format
					var ans1 =  this.userAnswers[this.currentIndex]
					for(var j=0;j<ans1.length;j++){
						if( j == ans1.length - 1 ){
							ans += options[ans1[j]].split(':')[0]
						} else {
							ans += options[ans1[j]].split(':')[0] + ','
						}
					}
				} else if( this.currentQuestion.type == 3 ) {
					ans = this.answers
				} else {
					if(  this.currentQuestion.content_format[this.userAnswers[this.currentIndex]]  != undefined ){
						ans = this.currentQuestion.content_format[this.userAnswers[this.currentIndex]].split(':')[0]
					}
				}
				if( this.types == 2 ){
					var answer  =  this.currentQuestion.answer.split('，').join(',')
					this.analysisShow = true
					answer = answer.replace(/[\s\u3000\u200B-\u200D\uFEFF]/g, '').replace(/[，,]/g, ',');
					if( answer ==  ans ){
						this.answerStatus = true
					} else {
						this.answerStatus = false
					}
				}
			},
			changeVal(item){
				this.userAnswers[item.id - 1] = this.answers;
			},
			
			shoucang(){
				this.questions[this.currentIndex].questions.is_collect  = 1
				uni.request({
					url: this.baseURL + '/api/paper/collect',
					method: 'GET',
					data: {appid: this.appid,question_id:this.currentQuestion.id},
					header: { 'Content-Type': 'application/json' },
					success: (res) => {
						uni.showToast({ title: '收藏成功！' });
					},
					fail: (err) => {
						console.error('请求失败:', err);
					}
				})
			},
			// 提交答案
			submitAnswers(ans) {
				//1 考试模式  2 练习模式
				var answer_model = ''
				if( this.types == 2 ){
					answer_model = 'run'
				} else if( this.types == 1 ){
					answer_model = 'exam'
				}
				var data = {
					answer: ans,
					paper_question_id: this.questions[this.currentIndex].id,
					appid: this.appid,
					answer_model: answer_model
				}
				this.questions[this.currentIndex].questions.is_answer = true
				uni.request({
					url: this.baseURL + '/api/paper/answer',
					method: 'POST',
					data: data,
					header: { 'Content-Type': 'application/json' },
					success: (res) => {	 console.log(res) },
					fail: (err) => {
						console.error('请求失败:', err);
					}
				})
			},
			//答题卡
			datika(){
				uni.navigateTo({
					url: '/pages/question/result?paper_id='+this.questions[0].paper_id
				})
			},
			records(ids){
				uni.request({
					url: this.baseURL + '/api/paper/recordList',
					method: 'GET',
					data: {appid: this.appid,paper_id:ids},
					header: { 'Content-Type': 'application/json' },
					success: (res) => {
						this.record = res.data.data
						this.initData(this.tmp)
						this.loading = false
					},
					fail: (err) => {
						console.error('请求失败:', err);
					}
				})
			},
			processHtmlImages(html) {
				let processed = html.replace(/<img[^>]*>/gi, match => {
					return match
						.replace(/(width|height|style)=["'][^"']*["']/gi, '')
						.replace(/(<img)/, '$1 @click="prviewImage(this)" style="max-width:100%!important;height:auto!important;display:block!important;margin:10rpx auto!important;"');
				});
				processed = html.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, src) => {
					return `<img 
					  style="max-width: 100%;height: auto;display: block;margin: 10px 0;" 
					  data-src="${src}" 
					  class="rich-image" 
					  src="${src}"
					>`
				  })
				processed = processed.replace(/style=(["'])[^"']*?\bwidth:[^;]+;?/gi, 'style=$1max-width:100%!important;');
				return processed;
			},
			handleImageClick() {
				uni.createSelectorQuery().selectAll('.analysis img') .fields({  dataset: true,src: true }, (res) => {
					const imgUrls =  res.map(item => item.dataset.src).filter(src => src != null && src !== '');
					if( imgUrls.length > 0 ){
						uni.previewImage({
							urls: imgUrls,
							longPressActions: {  
						        itemList: ['保存图片', '分享'],
						        success: (res) => {
									console.log(`选中操作: ${res.tapIndex}`);
						        }
							}
						});
					}
				}).exec(); 
			}
		},
		onLoad(options) {
			var appid = uni.getStorageSync('appid')
			this.paperTitle = options.title
			this.loading = true
			this.types = options.type
			var answer_model = ''
			if( options.type == 2 ){
				answer_model = 'run'
			} else if( options.type == 1 ){
				answer_model = 'exam'
			}
			uni.setStorageSync('answer_model',answer_model)
			uni.request({
				url: this.baseURL + '/api/paper/questionList',
				method: 'GET',
				data: {appid: this.appid,paper_id:options.id},
				header: { 'Content-Type': 'application/json' },
				success: (res) => {
					console.log(res.data.data)
					this.tmp = res.data.data
					this.records(options.id)
				},
				fail: (err) => {
					console.error('请求失败:', err);
				}
			})
		},
	};
</script>

<style>
	.container {height: 100vh;display: flex;flex-direction: column;background-color: #f5f5f5;}
	.nav-bar {padding: 20rpx 20rpx 10rpx 20rpx;background: #fff;text-align: center;border-bottom: 1rpx solid #eee;}
	.nav-bar .title {font-size: 30rpx;color: #3C3C3C;width: 100%;display: block;}
	.nav-bar .current {font-size: 26rpx;color: #989898;}
	.question{width: 100%;background: #fff;height: 100%}
	.question-title{width: 100%;display: flex;flex-direction: row;padding: 20rpx 0 20rpx 0;}
	.question-title .nums{width: 30rpx;height: 35rpx;background: #EB6E30;color: #fff;line-height: 40rpx;text-align: center;border-radius: 3rpx;font-size: 26rpx;margin-left: 10rpx;margin-top: 5rpx;}
	.question-title .title{font-size: 28rpx;margin-left: 10rpx;}
	.options{width: 90%;margin: 0 auto;}
	.options-radio{width: 90%;height: 80rpx;border: 1rpx solid #989898;border-radius: 2rpx;margin-top: 10rpx;margin-left: 10rpx;padding-left: 10rpx;}
	.analysis{width: 90%;margin: 0 auto;box-shadow: 0 10rpx 10rpx 0 #efefef;margin-top: 100rpx;border-radius: 10rpx;border: 1rpx solid #989898;position: relative;padding-bottom: 30rpx;}
	.tages{width: 200rpx;position: absolute;right: -10rpx;top: 20rpx;height: 60rpx;}
	.tages image{width: 100%;height: 100%;}
	.tages text{width: 100%;text-align: center;position: absolute;top: 0;display: block;color: #fff;font-size: 26rpx;line-height: 60rpx;}
	.answers{width: 100%;padding: 40rpx;display: flex;flex-direction: row;}
	.tt{position: relative;width: 80rpx;line-height: 40rpx;}
	.tt text{font-size: 34rpx;font-weight: bold;color: #10756A;position: absolute;left: 0;}
	.tt .lines{background:#63EFE2;height: 5rpx;width: 60rpx;position: absolute;left: 5rpx;top: 35rpx;opacity: .6;}
	.jiexi{width: 100%;padding: 0rpx 40rpx 40rpx 40rpx;display: flex;flex-direction: row;}
	.tta{font-size: 28rpx;color: #3C3C3C;width: 70%;}
	.bottom{width: 100%;position: fixed;height: 140rpx;bottom: 0;left: 0;display: flex;flex-direction: row;justify-content: space-around;padding-top: 20rpx;border-top: 1rpx solid #989898;background: #fff;}
	.bottom .icons{display: flex;flex-direction: column;}
	.bottom .icons image{width: 50rpx;height: 50rpx;display: block;margin: 0 auto;}
	.bottom .icons text{text-align: center;font-size: 26rpx;color: #3C3C3C;padding-top: 10rpx;}
	.options-container {margin-top: 20rpx;width: 90%;margin: 0 auto;}
	.option-item {display: flex;align-items: center;padding: 10px 0 10px 5px;margin-bottom: 20rpx;border: 1rpx solid #eee;border-radius: 12rpx;background: #fff;flex-direction: row;}
	.option-item.selected {border-color: #07c160;background: rgba(7, 193, 96, 0.05);}
	.option-circle {width: 40rpx;height: 40rpx;border: 2rpx solid #ddd;border-radius: 50%;margin-right: 20rpx;}
	.option-item.selected .option-circle {border-color: #07c160;background: #07c160;}
	.option-text {font-size: 30rpx;color: #333;}
	textarea{border: 1rpx solid #BEBEBE;padding: 20rpx;border-radius: 5rpx;width: 90%;margin: 0 auto;}
	.loading{width: 100%;height: 100%;position: fixed;top: 0;left: 0;}
	.modal{width: 100%;height: 100%;position: fixed;top: 0;left: 0;background: #000;opacity: .4;z-index: 2;}
	.loading .load{width: 100%;height: 50rpx;margin-top: 50%;z-index: 111;}
	.load image{width: 50rpx;height: 50rpx;display: block;margin: 0 auto;animation: rotate 1s linear infinite;}
	@keyframes rotate {from {transform: rotate(0deg);}to {transform: rotate(360deg);}}
</style>